/*
 *                        .::::.
 *                      .::::::::.
 *                     :::::::::::
 *                  ..:::::::::::'
 *               '::::::::::::'
 *                 .::::::::::
 *            '::::::::::::::..
 *                 ..::::::::::::.
 *               ``::::::::::::::::
 *                ::::``:::::::::'        .:::.
 *               ::::'   ':::::'       .::::::::.
 *             .::::'      ::::     .:::::::'::::.
 *            .:::'       :::::  .:::::::::' ':::::.
 *           .::'        :::::.:::::::::'      ':::::.
 *          .::'         ::::::::::::::'         ``::::.
 *      ...:::           ::::::::::::'              ``::.
 *     ````':.          ':::::::::'                  ::::..
 *                        '.:::::'                    ':'````..
 *
 * @Author: byx
 * @Date: 2022-12-14 21:19:35
 * @LastEditors: byx
 * @LastEditTime: 2023-01-09 21:00:48
 * @version: 1.0
 * @Descripttion: wwww.byx1024.top
 */
import { useFormik } from 'formik'
import * as Yup from 'yup'
import classnames from 'classnames'

import styles from './index.module.scss'
import NavBar from '@/components/NavBar/index'
import Input from '@/components/Input/index'
import { useDispatch } from 'react-redux'
import { sendValidationCode } from '@/store/action/login'
import { Toast } from 'antd-mobile'
import { useState } from 'react'
export default function Login() {
  // 2、Formik
  // 2.1 Formik 表单对象
  const formFormik = useFormik({
    // 设置表单字段的初始值
    initialValues: {
      mobile: '13900001111',
      code: '246810',
    },
    // 当表单提交的时候，会触发
    onSubmit: values => {
      console.log(formFormik)
      console.log('触发了提交：')
      console.log(values)
    },
    // 2.3 表单验证
    validationSchema: Yup.object().shape({
      // 手机号验证规则
      mobile: Yup.string()
        .required('请输入手机号')
        .matches(/^1[3456789]\d{9}$/, '手机号格式错误'),

      // 手机验证码验证规则
      code: Yup.string()
        .required('请输入验证码')
        .matches(/^\d{6}$/, '验证码6个数字'),
    }),
  })

  // 2.2 数据解构，也可以没有这步
  const {
    values: { mobile, code },
    handleChange,
    handleSubmit,
    handleBlur,
    touched,
    errors,
    isValid,
  } = formFormik

  // 1、组件input传递的事件-获取验证码
  const dispatch = useDispatch()
  const [time, setTime] = useState(0)

  const onExtraClick = async () => {
    // 是否在验证码倒计时
    if (time > 0) return
    // 发送请求-获取短信验证码
    // 1.1 先对手机号进行验证
    if (!/^1[3456789]\d{9}$/.test(mobile)) {
      formFormik.setTouched({
        mobile: true,
      })
      return
    }
    // 1.2 对结果的捕获
    try {
      // 成功
      await dispatch(sendValidationCode(mobile))
      Toast.success('验证码发送成功', 1)

      // 开启倒计时
      setTime(5)
      let timeId = setInterval(() => {
        // 当我们每次都想要获取到最新的状态，需要写成 箭头函数的形式
        setTime(time => {
          if (time === 1) {
            clearInterval(timeId)
          }
          return time - 1
        })
      }, 1000)
    } catch (error) {
      if (error.response) {
        Toast.info(error.response.data.message, 3)
      } else {
        Toast.info('服务器繁忙，请稍后重试')
      }
    }
  }
  return (
    <div className={styles.root}>
      {/* 测试代码： */}
      {/* <span className="iconfont icon-SEOpaiming"></span> */}
      {/* <svg className="icon" aria-hidden="true">
        <use xlinkHref="#icon-SEOpaiming"></use>
      </svg> */}
      {/* <Icon
        type="iconfanhui"
        className="big"
        onClick={() => {
          alert('提示了~')
        }}
      ></Icon> */}

      {/* 导航条 */}
      <NavBar>登录</NavBar>
      {/* 内容 */}
      <div className="content">
        <h3>短信登录</h3>
        <form onSubmit={handleSubmit}>
          <div className="input-item">
            <Input
              placeholder="请输入手机号"
              autoComplete="off"
              name="mobile"
              value={mobile}
              onChange={handleChange}
              onBlur={handleBlur}
            ></Input>
            {errors.mobile && touched.mobile && <div className="validate">{errors.mobile}</div>}
          </div>
          <div className="input-item">
            <Input
              placeholder="请输入验证码"
              autoComplete="off"
              name="code"
              value={code}
              extra={time === 0 ? '获取验证码' : `${time}s后获取`}
              onChange={handleChange}
              onBlur={handleBlur}
              onExtraClick={onExtraClick}
            ></Input>
            {errors.code && touched.code && <div className="validate">{errors.code}</div>}
          </div>
          {/* 登录按钮 */}
          <button
            type="submit"
            className={classnames('login-btn', { disabled: !isValid })}
            disabled={!isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
